package com.example.controller;

import com.example.service.DeadlockExampleService;
import com.example.service.ReadWriteLockExampleService;
import com.example.service.ReentrantReadWriteLockCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/read/write/lock/example")
public class ReadWriteLockExampleController {

    @Autowired
    private ReadWriteLockExampleService readWriteLockExampleService;
    @Autowired
    private ReentrantReadWriteLockCacheService reentrantReadWriteLockCacheService;
    @Autowired
    private DeadlockExampleService deadlockExampleService;

    // 读锁操作接口
    @GetMapping("/read-lock")
    public String readTask() {
        readWriteLockExampleService.readTask();
        return "ReadLock 示例任务已完成";
    }

    // 写锁操作接口
    @GetMapping("/write-lock")
    public String writeTask(@RequestParam int newValue) {
        readWriteLockExampleService.writeTask(newValue);
        return "WriteLock 示例任务已完成";
    }

    // 读取缓存数据接口
    @GetMapping("/read-cache")
    public String readCache() {
        return reentrantReadWriteLockCacheService.readData();
    }

    // 失效缓存接口
    @GetMapping("/invalidate-cache")
    public String invalidateCache() {
        reentrantReadWriteLockCacheService.invalidateCache();
        return "缓存已失效";
    }

    // 死锁测试接口
    @GetMapping("/deadlock-test")
    public String testDeadlock() {
        deadlockExampleService.simulateDeadlock();
        return "Deadlock 测试任务已启动";
    }
}
